package com.mall.canal.listener;

import com.alibaba.fastjson.JSON;
import com.mall.common.cons.ShopGoodsCons;
import com.mall.page.feign.PageFeign;
import com.mall.search.feign.SkuSearchFeign;
import com.mall.goods.model.Sku;
import com.mall.search.model.SkuEs;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

/**
 * @author Darren
 * @date 2022-08-22 15:48
 * Description：实时同步ES索引
 */
@Component
@CanalTable("sku")
public class SkuHandler implements EntryHandler<Sku> {
    @Autowired
    private SkuSearchFeign skuSearchFeign;
    @Autowired
    private PageFeign pageFeign;

    @SneakyThrows
    @Override
    public void insert(Sku sku) {
        if (sku.getStatus() != null && ShopGoodsCons.SKU_STATUS_NORMAL.equals(sku.getStatus())) {
            skuSearchFeign.addIndex(JSON.parseObject(JSON.toJSONString(sku), SkuEs.class));
        }
        // 商品详情静态页生成
        pageFeign.generateHtml(sku.getSpuId());
        System.out.println("sku canal insert success~");
    }

    @SneakyThrows
    @Override
    public void update(Sku before, Sku after) {
        // status等于1是添加索引，2和3都是删除索引
        if (after.getStatus() == null)
            return;
        if (ShopGoodsCons.SKU_STATUS_NORMAL.equals(after.getStatus())) {
            skuSearchFeign.addIndex(JSON.parseObject(JSON.toJSONString(after), SkuEs.class));
        } else if (ShopGoodsCons.SKU_STATUS_TAKE_DOWN.equals(after.getStatus()) ||
                ShopGoodsCons.SKU_STATUS_DELETE.equals(after.getStatus())) {
            skuSearchFeign.delIndex(after.getId());
        }
        // 商品详情静态页生成
        pageFeign.generateHtml(after.getSpuId());
        System.out.println("sku canal update success~");
    }

    @Override
    public void delete(Sku sku) {
        skuSearchFeign.delIndex(sku.getId());
        System.out.println("sku canal delete success~");
    }
}
